package com.borya.dao.impl;


import java.time.Clock;
import java.util.ArrayList;
import java.util.List;

import com.borya.model.entity.SelfRegistering;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.borya.dao.WebUserDAO;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerSqlSession;
import com.borya.model.db.Merchant;
import com.borya.model.db.Scope;
import com.borya.model.db.User;
import com.borya.util.DateUtils;
@Component("webUserDAOImpl")
public class WebUserDAOImpl extends BaseDAOImpl implements WebUserDAO{
	
	private Logger log = Logger.getLogger(getClass());
	
	@Override
	public String checkUser(String userName) {
		StringBuilder sb = new StringBuilder(256);
		sb.append("select phone from tf_sysuser_info where username=? limit 1");
		try (ServerSqlSession session = getSqlDataSource().session();){
			return session.executeQuery(sb.toString(), rs->{
				return (rs!=null && rs.next())? rs.getString("phone"):null;	
			},userName);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}
	
	
	@Override
	public Boolean checkPhone(String phone) {
		StringBuilder sb = new StringBuilder(256);
		sb.append("select id from tb_user_client where phone=? and flag=1 and source_type=1 limit 1");
		try(ServerSqlSession session = getSqlDataSource().session();) {
			return session.executeQuery(sb.toString(), rs-> {
				return (rs!=null && rs.next());
			}, phone);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}


	
	@Override
	public boolean insertUserInfo(User user, String papersCode,
			String remarks, String merchantCityCode) {		
		long time = user.getCreateTime();
		final String dealerId = user.getDealerId();
		final String userId = user.getUserId();
		
		int is_main = 1;
		StringBuilder sb = new StringBuilder(256);
		List<String> sql_list = new ArrayList<String>();
		if(user.getIsMain() == 1){
			//sb.delete(0, sb.length());
			sb.append("update tb_user_client set is_main=0 ");
			sb.append("where dealer_id='"+dealerId);
			sb.append("' and is_main=1 limit 1");
			sql_list.add(sb.toString());
		}else{
			is_main = 0 ;
		}				
		
		sb.delete(0, sb.length());
		sb.append("insert into tb_user_account set `user_id`='"+userId+"'");
		sql_list.add(sb.toString());
				
		sb.delete(0, sb.length());
		sb.append("insert into tb_user_client set ");
		sb.append("`userid`='"+userId);
		sb.append("',`phone`='"+user.getPhone());
		sb.append("',`dealer_id`='"+dealerId);
		sb.append("',`createtime`="+time);
		sb.append(",`citycode`='"+user.getCityCode());
		sb.append("',`cityname`='"+user.getCityName());
		sb.append("',`invite_code`='"+user.getInviteCode());
		sb.append("',`user_name`='"+user.getUserName());
		sb.append("',`last_time`="+time);
		sb.append(",`regist_time`="+time);
		sb.append(",`alipay_user_id`='"+user.getAlipayUserId());
		sb.append("',`weixin_user_id`='"+user.getWeixinUserId());
		sb.append("',`user_type_id`="+user.getUserTypeId()+",`is_main`="+is_main);
		sb.append(",merchant_id='").append(user.getMerchantId()).append("'");
		sql_list.add(sb.toString());
		
		
		sb.delete(0, sb.length());
		sb.append("insert into tb_user_client_detail set ");
		sb.append("`userid`='"+userId);
		sb.append("',`user_name`='"+user.getUserName());
		sb.append("',`createtime`="+time);
		sb.append(",`citycode`='"+user.getCityCode());
		sb.append("',`cityname`='"+user.getCityName());
		sb.append("',`paperscode`='"+papersCode);
		sb.append("',`user_type_id`="+user.getUserTypeId());
		sb.append(",`remarks`='"+remarks);
		sb.append("',`modifytime`="+time);
		sql_list.add(sb.toString());
		
		if(user.getIsMain() == 1 &&
				(StringUtils.isBlank(merchantCityCode)
				|| !"100".equals(merchantCityCode))){
			sb.delete(0, sb.length());
			sb.append("update tb_merchant set ");
			sb.append("`city_code`='").append(user.getCityCode()).append("'");
			sb.append(" where dealer_id='").append(dealerId).append("'");
			sb.append(" limit 1");
			sql_list.add(sb.toString());
		}
		
		int result[] = executeBatch(sql_list);
		return result != null && result.length>0;
	}

	@Override
	public Integer checkMerchantDealerId(String dealerID) {
		StringBuilder sb = new StringBuilder();
		sb.append("select id from tb_merchant where dealer_id=? limit 1");
		try(ServerSqlSession session = getSqlDataSource().session();) {
			return session.executeQuery(sb.toString(), (rs)->{
				return (rs != null && rs.next())?rs.getInt(1):0;
			}, dealerID);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}

	@Override
	public boolean insertMerchantInfo(SelfRegistering s) {
		StringBuilder sb = new StringBuilder(256);
		List<String> sql_list = new ArrayList<String>();
		Long now_time = Clock.systemDefaultZone().millis();
		sb.append("insert into tb_merchant set ");
		sb.append("`user_type_id`=").append(s.getUser_type_id());
		sb.append(",`dealer_id`='").append(s.getDealer_id()).append("'");
		sb.append(",`company_name`='").append(s.getCompany_name()).append("'");
		sb.append(",`business_licence`='").append(s.getIdCard()).append("'");
		sb.append(",`address`='").append(s.getAddress()).append("'");
		sb.append(",`store_address`='").append(s.getStoreAddress()).append("'");
		sb.append(",`popchannel`='").append(s.getPopchannel()).append("'");
		sb.append(",`head_popchannel`='").append(s.getHead_popchannel()).append("'");
		sb.append(",`createtime`=").append(now_time);
		sb.append(",`merchant_type`=").append(s.getMerchantType());
		sb.append(",`devMac`='").append(s.getDevMacAddress()).append("'");
		sb.append(",`popchannel_name`='").append(s.getPopchannel_name()).append("'");
		sb.append(",`head_popchannel_name`='").append(s.getHead_popchannel_name()).append("'");
		sb.append(",`regist_time`=").append(now_time);
		sb.append(",`merchant_attribute`=").append(s.getMerchant_attribute());
		sb.append(",`discount_model`='").append(s.getDiscountModel()).append("'");
		sb.append(",`phone_model`='").append(s.getPhoneModel()).append("'");
		sb.append(",`pack_model`='").append(s.getPackModel()).append("'");
		sb.append(",`dwk_model`='").append(s.getDwkModel()).append("'");
		sb.append(",`transfer_model`='").append(s.getTransterModel()).append("'");
		sb.append(",`city_code`='100'");
		sb.append(",`merchant_id`='").append(s.getMerchantId()).append("'");
		sb.append(",`ytsk_sub_merchantids`=''");
		//2018-10-25 白卡制卡费相关
		sb.append(",`white_card_pay`=").append(s.getWhiteCardPay());
		sb.append(",`white_card_return`=").append(s.getWhiteCardReturn());
		//2018-10-25 白卡制卡费相关
		sb.append(",`is_manage`=").append(s.getIsManage());
		sb.append(",`check_location_flag`=").append(s.getCheckLocationFlag());
		sb.append(",`check_location`=").append(s.getCheckLocation());
		sql_list.add(sb.toString());
		
		//继承popchannel的售卡权限
		final int type = s.getType();
		sb.delete(0, sb.length());
		sb.append("INSERT INTO tb_merchant_scope_config SET ");
		sb.append(" dealer_id = '"+s.getDealer_id()).append("', ");
		
		sb.append("scope_id =(select scope_id from  ");
		sb.append("(select scope_id from tb_sell_scope_pool where `type`=")
			.append(type).append(" and area like '%")
			.append(s.getScope()).append("%' limit 1) ");
		sb.append("as temp)");
		sb.append(",create_time=").append(s.getModifyTime());
		if(type==1){//远特卡全国可开卡
			sb.append(",is_local=").append(0);
			sb.append(",cus_on_off=").append(0);
		}else{
			sb.append(",is_local=").append(1);
			sb.append(",cus_on_off=").append(1);
		}
		sql_list.add(sb.toString());
		
		sb.delete(0, sb.length());
		sb.append("insert into tb_merchant_account set `dealer_id`='");
		sb.append(s.getDealer_id());
		sb.append("',`update_date`='"+DateUtils.formatDateByFormat(now_time, "yyyyMMdd"));
		sb.append("'");
		sb.append(",`merchant_id`='").append(s.getMerchantId()).append("'");
		sql_list.add(sb.toString());
		
		sb.delete(0, sb.length());
		sb.append("update ib_kameng_deliveryrecord set ");
		sb.append("`kmstate`='").append(1);
		sb.append("',`ActivationTime`='").append(DateUtils.format(now_time, "yyyy-MM-dd HH:mm:ss"));
		sb.append("' where `KMRecordCode`='").append(s.getDevMacAddress()).append("'");
		sql_list.add(sb.toString());
		/**********授权牌初始信息************/
		sb.delete(0,sb.length());
		sb.append("insert into tb_merchant_shqp set ");
		sb.append("dealer_id='").append(s.getDealer_id()).append("'");
		sb.append(",modify_time=").append(s.getModifyTime());
		sb.append(",device_id='").append(s.getDevMacAddress()).append("'");
		sql_list.add(sb.toString());
		/**********授权牌初始信息************/
		int result[] = executeBatch(sql_list);
		return result != null && result.length>0;
	}

	@Override
	public Boolean checkUserIsAdmin(String dealerID) {
		StringBuilder sb = new StringBuilder(256);
		sb.append("select id from tb_user_client ");
		sb.append("where dealer_id=? limit 1");
		try (ServerSqlSession session = getSqlDataSource().session();){
			return session.executeQuery(sb.toString(),rs-> {
				return (rs!=null && rs.next());
			}, dealerID);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}

	@Override
	public Merchant getMerchantTypeId(String dealerID) {
		StringBuilder sb = new StringBuilder();
		sb.append("select `user_type_id`,city_code,merchant_id from tb_merchant where dealer_id=? limit 1");
		try (ServerSqlSession session = getSqlDataSource().session();){
			return session.executeQuery(sb.toString(), rs-> {
				if(rs!=null && rs.next()){
					Merchant m = new Merchant();
					m.setUserTypeId(rs.getInt("user_type_id"));
					m.setCityCode(rs.getString("city_code"));
					m.setMerchantId(rs.getString("merchant_id"));
					return m;
				}
				return null;
			}, dealerID);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}
	

	@Override
	public List<Scope> findScopePool() {
		String sql="select * from tb_sell_scope_pool";
		try (ServerSqlSession session = getSqlDataSource().session();){
			return session.executeQuery(sql, rs-> {
				List<Scope> scopes=new ArrayList<>();
				if(rs!=null){
					while(rs.next()){
						Scope scope = new Scope();
						scope.setScopeId(rs.getString("scope_id"));
						scope.setType(rs.getInt("type"));
						scope.setArea(rs.getString("area"));
						scope.setRemark(rs.getString("remark"));
						scopes.add(scope);
					}
				}
				return scopes;
			});
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}


	@Override
	public Scope checkScope(int type, String scope) {
		String sql="select * from tb_sell_scope_pool where `type`=? and area like ? limit 1";
		try (ServerSqlSession session = getSqlDataSource().session();){
			return session.executeQuery(sql, rs-> {
				if(rs!=null && rs.next()){
					//id,scope_id,type,area,create_time,modify_time,remark,white_list
					Scope sp = new Scope();
					
					sp.setArea(rs.getString("area"));
					sp.setType(rs.getInt("type"));
					sp.setRemark(rs.getString("remark"));
					sp.setScopeId(rs.getString("scope_id"));
					sp.setPhoneModel(rs.getString("phone_model"));
					sp.setPackModel(rs.getString("pack_model"));
					
					return sp;
				}
				return null;
			},type,"%"+scope+"%");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return null;
		}
	}
}